const tbody = document.querySelector('.list')
const total = document.querySelector('.total')

//渲染学生列表
const getStudentList = async () => {
  const { data: res } = await axios({
    url: '/students',
  })
  const studentStr = res.data
    .map((item) => {
      return `
    <tr>
    <td>${item.name}</td>
    <td>${item.age}</td>
    <td>${item.gender ? '男' : '女'}</td>
    <td>第${item.group}组</td>
    <td>${item.hope_salary}</td>
    <td>${item.salary}</td>
    <td>${item.province + item.city + item.area}</td>
    <td>
      <a href="javascript:;" class="text-success mr-3"
        ><i class="bi bi-pen" data-id="${item.id}"></i
      ></a>
      <a href="javascript:;" class="text-danger"><i class="bi bi-trash" data-id="${
        item.id
      }"></i></a>
    </td>
  </tr>`
    })
    .join('')
  tbody.innerHTML = studentStr
  total.innerHTML = res.data.length
}
getStudentList()
//易错点：<td>${item.gender?'男':'女'}</td>  此处性别渲染页面，男 0,布尔值为false,女 1 布尔值为true，用三元运算 //

//--------初始化模态框 & 城市选择
// bootstrap的模态框直接cv即可
const modalBox = document.querySelector('#modal')
const modal = new bootstrap.Modal(modalBox)
const ps = document.querySelector('[name=province]')
const cs = document.querySelector('[name=city]')
const as = document.querySelector('[name=area]')
const openmodal = document.querySelector('#openModal')
const submitBtn = document.querySelector('#submit')

//点击页面的加号打开模态框进行学生信息的填写
openmodal.addEventListener('click', function () {
  cs.innerHTML = `<option value="">--城市--</option>`
  as.innerHTML = `<option value="">--地区--</option>`
  //获取下拉框的省市区信息
  const provinceList = async () => {
    const { data: res } = await axios({
      url: '/api/province',
    })
    const provinceStr = res.list
      .map((item) => {
        return `<option value="${item}">--${item}--</option>`
      })
      .join('')
    ps.innerHTML = `<option value="">--省份--</option>+${provinceStr}`

    ps.addEventListener('change', async function () {
      const { data: res } = await axios({
        url: '/api/city',
        params: { pname: ps.value },
      })

      const cityStr = res.list
        .map((item) => {
          return `<option value="${item}">--${item}--</option>`
        })
        .join('')
      cs.innerHTML = `<option value="">--城市--</option>${cityStr}`
    })

    cs.addEventListener('change', async function () {
      const { data: res } = await axios({
        url: '/api/area',
        params: { pname: ps.value, cname: cs.value },
      })
      const areaStr = res.list
        .map((item) => {
          return `<option value="${item}">--${item}--</option>`
        })
        .join('')
      as.innerHTML = `<option value="">--地区--</option>${areaStr}`
    })
  }
  provinceList()
  modal.show()
  form.reset()
  //----修改学生-----------------------------------------------------------------
  modalBox.dataset.id = 'add'
  modalBox.querySelector('.modal-title').innerHTML = '添加学员'          //限定了弹框的类型为add 添加
  //----修改学生-----------------------------------------------------------------
})

//点击提交按钮上传学生数据
submitBtn.addEventListener('click', async function () {
  const data = serialize(form, { hash: true })
  //易错点：发送过去的数据有符合要求的数据类型//
  if (!data.name) return alert('姓名不能为空')
  if (!data.age) return alert('年龄不能为空')
  if (!data.hope_salary) return alert('期望薪资不能为空')
  if (!data.salary) return alert('薪资不能为空')
  if (data.group < 1 || data.group > 8) return alert('请输入1-8之间的组号')
  data.age = +data.age
  data.gender = +data.gender
  data.hope_salary = +data.hope_salary
  data.salary = +data.salary
  data.group = +data.group
  //- 修改学生--------------------------------------------------------------------
  if (modalBox.dataset.id === 'add') {           //限定了弹框的类型为add 添加
    const { data: res } = await axios({
      url: '/students',
      method: 'post',
      data,
    })
    alert(res.message)
    getStudentList()
    modal.hide()
  } else {
    const { data: res } = await axios({
      url: '/students/' + modalBox.dataset.id,      //这里的ID是modalBox.dataset.id
      method: 'put',
      data,
    })
    getStudentList()
    modal.hide()
    //- 修改学生-----------------------------------------------------------------------------
  }
})

//页面的两个图表按钮
tbody.addEventListener('click', async function (e) {
  // 修改学生信息----先把信息还原到模态框
  if (e.target.classList.contains('bi-pen')) {
    const id = e.target.dataset.id
    const { data: res } = await axios({
      url: '/students/' + id,
    })
    const nodeList = modalBox.querySelectorAll('[name]')
    //给所有的表单输入框赋值
    nodeList.forEach((item) => {
      //性别判断                                              //难点----我不是很懂，不熟悉//
      if (item.name === 'gender') {
        res.data[item.name]
          ? (modalBox.querySelector('#cb01').checked = true)
          : (modalBox.querySelector('#cb02').checked = true)
      }
      item.value = res.data[item.name] //易错点： res.data.[item.name]//
    })
    //省市区重新渲染到模态框
    const {
      data: { list: provincedata },
    } = await axios({
      url: '/api/province',
    })
    const provinceStr = provincedata
      .map((item) => {
        return `<option value="${item}">--${item}--</option>`
      })
      .join('')
    ps.innerHTML = `<option value="">--省份--</option>+${provinceStr}`
    ps.value = res.data.province

    const {
      data: { list: citydata },
    } = await axios({
      url: 'api/city',
      params: { pname: res.data.province },
    })
    const cityStr = citydata.map((item) => {
      return `  <option value="${item}">--${item}--</option>`
    })
    cs.innerHTML = `<option value="">--城市--</option>${cityStr}`
    //给下拉框赋值
    cs.value = res.data.city

    const {
      data: { list: areadata },
    } = await axios({
      url: 'api/area',
      params: { pname: res.data.province, cname: res.data.city },
    })
    const areaStr = areadata.map((item) => {
      return `  <option value="${item}">--${item}--</option>`
    })
    as.innerHTML = `<option value="">--城市--</option>${areaStr}`
    //给下拉框赋值
    as.value = res.data.area
    //---------------------------------------------------------------------------修改学员信息
    modalBox.dataset.id = id
    modalBox.querySelector('.modal-title').innerHTML = '编辑学员信息'
    //---------------------------------------------------------------------------修改学员信息
    modal.show()
    //todo
  }
  //删除学生信息
  else if (e.target.classList.contains('bi-trash')) {
    const id = e.target.dataset.id
    const res = await axios({
      url: '/students/' + id,
      method: 'DELETE',
    })
    alert('成功删除学生')
    getStudentList()
  }
})
